package com.weijun.keepalive

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.PowerManager
import android.os.Process

/**
 * @author: weijun
 * date: 2023/7/5
 * description:
 */
internal const val CLICK_NOTIFICATION = "CLICK_NOTIFICATION"
internal const val ACTION_SCREEN_ON = "_ACTION_SCREEN_ON"
internal const val ACTION_SCREEN_OFF = "_ACTION_SCREEN_OFF"
internal const val NOTIFY_LEVEL = 13691
internal const val LOCAL_SERVICE_NAME = "com.weijun.keepalive.service.LocalService"

infix fun Context.isServiceRunning(className:String) :Boolean {
    val servicesList = (getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getRunningServices(Int.MAX_VALUE)
    if (servicesList != null) {
        val iterator: Iterator<ActivityManager.RunningServiceInfo> = servicesList.iterator()
        while (iterator.hasNext()) {
            val serviceInfo = iterator.next()
            if (className == serviceInfo.service.className) {
                return true
            }
        }
    }
    return false
}

infix fun Context.isRunningTaskExist(processName:String) :Boolean {
    val processList = (getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).runningAppProcesses
    if (processList != null) {
        for (info in processList) {
            if (info.processName == processName) {
                return true
            }
        }
    }
    return false
}

fun Context.isScreenOn():Boolean {
    return try {
        (applicationContext.getSystemService(Activity.POWER_SERVICE) as PowerManager).isScreenOn
    } catch (ignore: Exception) {
        true
    }
}

fun Application.isMainProcess():Boolean {
    var processName = ""
    val mActivityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    if (mActivityManager.runningAppProcesses != null) {
        for (appProcess in mActivityManager.runningAppProcesses) {
            if (appProcess.pid == Process.myPid()) {
                processName = appProcess.processName
                break
            }
        }
        if (processName == packageName) {
            return true
        }
    }
    return false
}